<template>
  <div class="container">
    <canvas
      ref="canvas"
      @mousedown="onMouseDown"
      @mousemove="onMouseMove"
      @mouseup="onMouseUp"
      @mouseout="onMouseUp"
      :width="canvasWidth"
      :height="canvasHeight"
    >
    </canvas>
  </div>
</template>

<script>
export default {
  data() {
    return {
      canvasWidth: 500,
      canvasHeight: 500,
      lineStart: { x: 100, y: 100 },
      lineEnd: { x: 400, y: 400 },
      isDraggingStart: false,
      isDraggingEnd: false,
      lastMousePos: { x: 0, y: 0 },
    };
  },
  mounted() {
    this.canvas = document.querySelector("canvas");
    // 绘制线条
    this.drawLine(this.lineStart, this.lineEnd);
  },
  methods: {
    /**
     * 绘制线条
     */
    drawLine(start, end) {
      const ctx = this.canvas.getContext("2d");
      ctx.lineWidth = 5;
      ctx.strokeStyle = "black";
      ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
      // 画线条
      ctx.strokeStyle = "skyblue";
      ctx.beginPath();
      ctx.moveTo(start.x, start.y);
      ctx.lineTo(end.x, end.y);
      ctx.stroke();
      // 画起点圆环
      ctx.fillStyle = "#fff";
      ctx.beginPath();
      ctx.arc(start.x, start.y, 5, 0, Math.PI * 2);
      ctx.stroke();
      ctx.fill();
      // 画终点圆环
      ctx.beginPath();
      ctx.arc(end.x, end.y, 5, 0, Math.PI * 2);
      ctx.stroke();
      ctx.fill();
    },
    /**
     * 鼠标按下事件
     */
    onMouseDown(e) {
      const mousePos = this.getMousePosition(e);
      if (this.isPointInCircle(mousePos, this.lineStart)) {
        this.isDraggingStart = true;
      } else if (this.isPointInCircle(mousePos, this.lineEnd)) {
        this.isDraggingEnd = true;
      }
      this.lastMousePos = mousePos;
    },
    /**
     * 鼠标移动事件
     */
    onMouseMove(e) {
      const mousePos = this.getMousePosition(e);
      if (this.isDraggingStart) {
        this.lineStart.x += mousePos.x - this.lastMousePos.x;
        this.lineStart.y += mousePos.y - this.lastMousePos.y;
        this.drawLine(this.lineStart, this.lineEnd);
      } else if (this.isDraggingEnd) {
        this.lineEnd.x += mousePos.x - this.lastMousePos.x;
        this.lineEnd.y += mousePos.y - this.lastMousePos.y;
        this.drawLine(this.lineStart, this.lineEnd);
      }
      this.lastMousePos = mousePos;
    },
    /**
     * 鼠标松开事件
     */
    onMouseUp() {
      this.isDraggingStart = false;
      this.isDraggingEnd = false;
    },
    /**
     * 获取鼠标在画布内的坐标
     */
    getMousePosition(e) {
      const rect = e.target.getBoundingClientRect();
      return { x: e.clientX - rect.left, y: e.clientY - rect.top };
    },
    /**
     * 判断点是否在圆内
     */
    isPointInCircle(point, circle) {
      const dx = point.x - circle.x;
      const dy = point.y - circle.y;
      return dx * dx + dy * dy < 100; // 100是圆的半径平方，可根据需要调整
    },
  },
};
</script>

<style>
.container {
  display: flex;
  justify-content: center;
  align-items: center;
}
canvas {
  border: 1px solid #ccc;
}
</style>
